// Copyright (c) 2012-2013, yuno. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of contributors
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
package sugarmintcandy.widgetwindow;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CreateShortcutActivity extends Activity implements
	DialogInterface.OnCancelListener, DialogInterface.OnClickListener {
    private Item[] mItems;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	showDialog(R.id.create_shortcut);
    }

    @Deprecated
    @Override
    protected Dialog onCreateDialog(int id) {
	if (id == R.id.create_shortcut) {
	    ArrayList<Item> items = new ArrayList<Item>();
	    items.add(createItemToOpenWindow());
	    items.add(createItemToHideAllWindows());
	    for (int i = 1; i <= 10; i++) {
		items.add(createItemToSwitchWorkspace(i));
	    }
	    MainDatabase db = ((MainApplication) getApplication())
		    .getDatabase();
	    WindowInfo[] infoList = db.getWindowInfoList();
	    Collections.reverse(Arrays.asList(infoList));
	    for (WindowInfo info : infoList) {
		items.add(createItemToShowWindow(info));
	    }
	    for (WindowInfo info : infoList) {
		items.add(createItemToHideWindow(info));
	    }
	    mItems = items.toArray(new Item[items.size()]);
	    MyAdapter adapter = new MyAdapter(mItems);
	    AlertDialog.Builder d = new AlertDialog.Builder(this);
	    d.setTitle(R.string.shortcut_name);
	    d.setCancelable(true);
	    d.setOnCancelListener(this);
	    d.setAdapter(adapter, this);
	    return d.create();
	}
	return super.onCreateDialog(id);
    }

    @Override
    public void onCancel(DialogInterface dialog) {
	finish();
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
	setResult(RESULT_OK, createResult(mItems[which]));
	finish();
    }

    private Intent createResult(Item item) {
	Intent result = new Intent();
	result.putExtra(Intent.EXTRA_SHORTCUT_NAME, item.text);
	result.putExtra(Intent.EXTRA_SHORTCUT_INTENT, item.intent);
	if (item.icon != 0) {
	    Bitmap bitmap = createIconBitmap(item);
	    result.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);
	}
	return result;
    }

    private Item createItemToOpenWindow() {
	Intent intent = new Intent(this, ShortcutActivity.class);
	intent.setAction(Constants.ACTION_OPEN_WINDOW);
	Item item = new Item();
	item.intent = intent;
	item.text = getString(R.string.open_window);
	item.packageName = getPackageName();
	item.icon = R.drawable.shortcut_open;
	return item;
    }

    private Item createItemToHideAllWindows() {
	Intent intent = new Intent(this, ShortcutActivity.class);
	intent.setAction(Constants.ACTION_HIDE_ALL_WINDOWS);
	Item item = new Item();
	item.intent = intent;
	item.text = getString(R.string.hide_all_windows);
	item.packageName = getPackageName();
	item.icon = R.drawable.shortcut_close;
	return item;
    }

    private static final int[] workspaceNames = { R.string.workspace_1,
	    R.string.workspace_2, R.string.workspace_3, R.string.workspace_4,
	    R.string.workspace_5, R.string.workspace_6, R.string.workspace_7,
	    R.string.workspace_8, R.string.workspace_9, R.string.workspace_10 };

    private static final int[] workspaceIcons = { R.drawable.shortcut_1,
	    R.drawable.shortcut_2, R.drawable.shortcut_3,
	    R.drawable.shortcut_4, R.drawable.shortcut_5,
	    R.drawable.shortcut_6, R.drawable.shortcut_7,
	    R.drawable.shortcut_8, R.drawable.shortcut_9,
	    R.drawable.shortcut_10 };

    private Item createItemToSwitchWorkspace(int workspace) {
	Intent intent = new Intent(this, ShortcutActivity.class);
	intent.setAction(Constants.ACTION_SWITCH_WORKSPACE);
	intent.putExtra(Constants.EXTRA_WORKSPACE, workspace);
	Item item = new Item();
	item.intent = intent;
	item.text = getString(workspaceNames[workspace - 1]);
	item.packageName = getPackageName();
	item.icon = workspaceIcons[workspace - 1];
	return item;
    }

    private Item createItemToShowWindow(WindowInfo info) {
	Intent intent = new Intent(this, ShortcutActivity.class);
	intent.setAction(Constants.ACTION_SHOW_WINDOW);
	intent.putExtra(Constants.EXTRA_APPWIDGETID, info.appWidgetId);
	Item item = new Item();
	item.intent = intent;
	item.text = getString(R.string.show_something, info.getTitleBarText());
	if (info.providerInfo != null) {
	    item.packageName = info.providerInfo.provider.getPackageName();
	    item.icon = info.providerInfo.icon;
	} else {
	    item.icon = android.R.drawable.ic_menu_help;
	}
	item.windowColor = info.windowColor;
	item.titleBarColor = info.titleBarColor;
	return item;
    }

    private Item createItemToHideWindow(WindowInfo info) {
	Intent intent = new Intent(this, ShortcutActivity.class);
	intent.setAction(Constants.ACTION_HIDE_WINDOW);
	intent.putExtra(Constants.EXTRA_APPWIDGETID, info.appWidgetId);
	Item item = new Item();
	item.intent = intent;
	item.text = getString(R.string.hide_something, info.getTitleBarText());
	if (info.providerInfo != null) {
	    item.packageName = info.providerInfo.provider.getPackageName();
	    item.icon = info.providerInfo.icon;
	} else {
	    item.icon = android.R.drawable.ic_menu_help;
	}
	item.overlay = R.drawable.shortcut_close_overlay;
	item.windowColor = info.windowColor;
	item.titleBarColor = info.titleBarColor;
	return item;
    }

    @SuppressLint("NewApi")
    private Bitmap createIconBitmap(Item item) {
	try {
	    int iconSize = ApiHelper.getLauncherLargeIconSize(this);
	    Bitmap bitmap = Bitmap.createBitmap(iconSize, iconSize,
		    Bitmap.Config.ARGB_8888);
	    Canvas canvas = new Canvas(bitmap);
	    canvas.drawARGB(0, 0, 0, 0);
	    int p1 = 0;
	    int p2 = iconSize / 12;
	    int p3 = iconSize;
	    if (item.titleBarColor != 0) {
		Paint paint = new Paint();
		paint.setColor(item.titleBarColor);
		paint.setStyle(Paint.Style.FILL);
		canvas.drawRect(p1, p1, p3, p2, paint);
	    }
	    if (item.windowColor != 0) {
		Paint paint = new Paint();
		paint.setColor(item.windowColor);
		paint.setStyle(Paint.Style.FILL);
		canvas.drawRect(p1, p2, p3, p3, paint);
	    }
	    if (item.icon != 0) {
		Context context = this;
		if (item.packageName != null) {
		    context = createPackageContext(item.packageName, 0);
		}
		Bitmap icon = BitmapFactory.decodeResource(
			context.getResources(), item.icon);
		if (icon != null) {
		    int sw = icon.getWidth();
		    int sh = icon.getHeight();
		    float dw = p3 - p1;
		    float dh = p3 - p2;
		    if (dw * sh < dh * sw) {
			dh = dw * sh / sw;
		    } else {
			dw = dh * sw / sh;
		    }
		    float dx = (p1 + p3 - dw) / 2;
		    float dy = (p2 + p3 - dh) / 2;
		    Paint paint = new Paint();
		    paint.setFilterBitmap(true);
		    canvas.drawBitmap(icon, new Rect(0, 0, sw, sh), new RectF(
			    dx, dy, dx + dw, dy + dh), paint);
		}
	    }
	    if (item.overlay != 0) {
		Bitmap icon = BitmapFactory.decodeResource(getResources(),
			R.drawable.shortcut_close_overlay);
		if (icon != null) {
		    int w = icon.getWidth();
		    int h = icon.getHeight();
		    int dx = p3 - w;
		    int dy = p1;
		    canvas.drawBitmap(icon, new Rect(0, 0, w, h), new Rect(dx,
			    dy, dx + w, dy + h), new Paint());
		}
	    }
	    return bitmap;
	} catch (Throwable ex) {
	    Debug.warn(ex);
	    return null;
	}
    }

    private static class Item {
	Intent intent;
	String text;
	String packageName;
	int icon;
	int overlay;
	int windowColor;
	int titleBarColor;
    }

    private class MyAdapter extends BaseAdapter {
	private Item[] mItems;

	MyAdapter(Item[] items) {
	    mItems = items;
	}

	@Override
	public int getCount() {
	    return mItems.length;
	}

	@Override
	public Item getItem(int position) {
	    return mItems[position];
	}

	@Override
	public long getItemId(int position) {
	    return position;
	}

	@Override
	public View getView(int position, View view, ViewGroup parent) {
	    Context context = parent.getContext();
	    if (view == null) {
		LayoutInflater inflater = LayoutInflater.from(context);
		view = inflater.inflate(R.layout.create_shortcut_item, parent,
			false);
	    }
	    ImageView imageView = (ImageView) view
		    .findViewById(R.id.image_view);
	    TextView textView = (TextView) view
		    .findViewById(android.R.id.text1);
	    Item item = getItem(position);
	    Bitmap bitmap = createIconBitmap(item);
	    imageView.setImageBitmap(bitmap);
	    textView.setText(item.text);
	    return view;
	}
    }
}
